<template>
  <div>
    <div class="flex mb-5 justify-between">
      <div class="mt-5 curror-pointer" @click="onSelectAll">
        <span style="color: #000;">全选</span>
        <a-checkbox
          class="ml-5"
          :checked="is_allChecked"
          @change="onChange"
        ></a-checkbox>
      </div>
        <a-button type="primary" style="margin-top: 1px" @click="onSave"
        >保存到素材库</a-button
      >
    </div>
    <div class="video-list">
      <div class="video-list-item" v-for="(item, index) in list" :key="index">
        <div
          class="video-list-item__content"
          @mouseover="playVideo(index)"
          @mouseleave="pauseVideo(index)"
          v-if="item.status === 2"
        >
          <video :src="item.media_url" class="video" :id="`video_${index}`"></video>
        </div>
        <div v-else class="error-msg">
          <a-popover>
            <template #content>{{ item.status_msg }}</template>
            <exclamation-circle-filled class="curror-pointer" />
            <span class="ml-5 curror-pointer">{{ item.status_txt }}</span>
          </a-popover>
        </div>
        <div class="video-list-item__bottom" >
          <div class="video-tip">
           <span :title="getLanuage(item.target_language)">{{ getLanuage(item.target_language) }}</span>
           <span class="ml-10 time"  v-if="item.status==2" :title="item.duration_txt"> {{ item.duration_txt }}</span>
          </div>
          <div class="btn-area">
            <a-checkbox
        
            :disabled="item.status != 2"
            :checked="checkedIds.includes(item.id)"
            @change="handleCheck(item.id)"
          ></a-checkbox>
              <span v-if="item.status==2" class="preview-btn" @click="previewVideo(item)">
              <eye-outlined />
              预览
            </span>
            <MoreButton :data="item" v-if="item.status==2" :excludeNames="['VideoTranslateIndex']" buttonType="icon"></MoreButton>
          </div>
        </div>
      </div>
    </div>
    <MaterialsModule
      ref="materialsRef"
      :material_type="'video'"
      requestType
      :data="{ material_url: cropVideoUrl, autoName: video_name }"
      @selfRequest="handleSelfRequest"
      :visible="saveVisible"
      jobCategory="videoSplit"
      @onCancel="saveVisible = false"
    />
    <PreviewModal
      :visible="previewVisible"
      title="预览"
      :url="previewUrl"
      type="video"
      @onCancel="previewVisible = false"
    />
  </div>
</template>
<script setup>
import {
  DownloadOutlined,
  EyeOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import request from "@/common/utils/request";
import dayjs from "dayjs";
import PreviewModal from "@/components/PreviewModal/index.vue";
import { ref, inject,onUnmounted } from "vue";
import MaterialsModule from "../../components/MaterialsModule/materialLibraryModal.vue";
import { languageList as langList } from "../utils/index.js";
import MoreButton from "@/views/shotstack/CreationCenter/components/routeToButton.vue";
const props = defineProps({
  list: {
    type: Array,
    default: () => [],
  },
});

let previewVisible = ref(false);
let checkedIds = ref([]);
let is_allChecked = ref(false);
let saveVisible = ref(false);
let video_name = ref("");
let cropVideoUrl = ref("");
let previewUrl = ref("");
let materialsRef = ref(null);
let languageList = langList;
const getLanuage = (value) => {
  return languageList.find((item) => item.value === value)?.label;
}
const requestUploadVideo = (params) => {
  return new Promise((resolve, reject) => {
    request
      .post("/work_ai", "/material/upload", params)
      .then((res) => {
        resolve(res);
      })
      .catch(() => {
        reject("上传失败");
      
      });
  });
};
const handleSelfRequest = async (params) => {
  let allRequest = checkedIds.value.map((item,index) => {
      return requestUploadVideo({
        ...params,
        file_urls: [
            {
                material_url: props.list.find((i) => i.id === item)?.media_url,
                material_name:  dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss") + '_'+ (index + 1),
                type: "video",
            }
        ],
      })
  })
  await Promise.all(allRequest);
  materialsRef.value.stopLoding();
  saveVisible.value = false;
  message.success("保存成功");
};
const onChange = (e) => {
  is_allChecked.value = e.target.checked;
  if (is_allChecked.value) {
    checkedIds.value = props.list.filter((item) => item.status === 2).map((item) => item.id);
  } else {
    checkedIds.value = [];
  }
};
const onSelectAll = () => {
  is_allChecked.value = !is_allChecked.value;
  if (is_allChecked.value) {
    checkedIds.value = props.list.filter((item) => item.status === 2).map((item) => item.id);
  } else {
    checkedIds.value = [];
  }
};
const handleCheck = (item) => {
  if (!checkedIds.value.includes(item)) {
    checkedIds.value.push(item);
  } else {
    checkedIds.value = checkedIds.value.filter((id) => id !== item);
  }
  if (checkedIds.value.length === props.list.filter((item) => item.status === 2).length) {
    is_allChecked.value = true;
  } else {
    is_allChecked.value = false;
  }
};
const playVideo = (index) => {
  const video = document.getElementById(`video_${index}`);
  if (video.paused) {
    video.play();
  }
};
const pauseVideo = (index) => {
  const video = document.getElementById(`video_${index}`);
  if (!video.paused) {
    video.pause();
  }
};
const onSave = () => {
  if (!checkedIds.value.length) {
    return message.warning("请选择素材");
  }
  saveVisible.value = true;
};
const downloadVideo = async (item) => {
  const videoUrl = item.media_url;
      const filename =
      getLanuage(item.target_language) + "_" + dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
      const fileUrl = videoUrl;
      item.loading = true;
      let blob = null;
      try {
        const response = await fetch(fileUrl); // 获取视频链接
        blob = await response.blob(); // 将响应转为 Blob
      } catch (e) {
       item.loading = false;
        return message.error("视频下载失败，请稍后再试");
      }

      const url = window.URL.createObjectURL(blob); // 创建一个 blob URL
      const link = document.createElement("a");
      link.href = url; // 设置 href 为 blob URL
      link.download = filename; // 可选，设置下载时的文件名
      document.body.appendChild(link);
      link.click(); // 模拟点击下载
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url); // 清理
      item.loading = false; 
}
const previewVideo = (item)=>{
  previewUrl.value = item.media_url;
  previewVisible.value = true;
}
onUnmounted(() => {
  checkedIds.value = [];
  is_allChecked.value = false;
  saveVisible.value = false; 
})
</script>
<style lang="less" scoped>
.video-list {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
  .video-list-item {
    position: relative;
    width: 100%;
    height: 260px;
    display: flex;
    flex-direction: column;
    border-radius: 5px;
    background: #000;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
    // border: 1px solid #ccc;
    .video {
      width: 100%;
      height: 100%;
      border-radius: 5px;
    }
    .video-list-item__content {
      height: calc(100% - 45px);
      cursor: pointer;
      min-width: 200px;
      box-sizing: border-box;
    }
    .video-list-item__bottom {
      height: 45px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      border-radius: 0 0 3px 3px;
    //   border: 1px solid rgba(0, 0, 0, 0.2);
      background: #fff;
      padding: 0 10px;
      :deep(.ss-btn) {
        padding-left: 0px!important;
       span{
        margin-left: unset!important;
       }
      }
    }
  }
}
.curror-pointer {
  cursor: pointer;
}
.error-msg{
  display: flex;
  justify-content: center;
  align-items: center;
  flex:1;
  color: red;
  font-size: 16px;
  min-width: 200px;
}
.video-tip{
 
  overflow: hidden;
  max-width: 100px;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
  color: #333;
  .time{
    color: #aaa;
  }
}
.preview-btn{
  color: var(--ss-primary-color);
  cursor: pointer;
  margin-left: 10px;
  font-size: 14px;
  margin-right: 5px;
}
.video-preview{
  width: 600px;
  height: 400px;
  video{
    width: 100%;
    height: 100%;
  }
}
.btn-area{
  flex-shrink: 0;
}
</style>
